<?php
/**
 * 应用服务
 */

namespace app\common\services;

use Exception;
use hiduoke\services\UploadService;
use think\facade\Config;
use think\facade\Db;

/**
 * 附件
 * @package app\common\services
 * User: liuhongbin
 * Date: 2021-05-26 9:45
 */
class Attachment
{
    /**
     * @var \think\App
     */
    public $app;
    //数据库前缀
    public $prefix;
    //0文件， 1图片，2音乐，3视频
    public $types = array(
        0 => 'file',
        1 => "image",
        2 => "audio",
        3 => "video"
    );


    public function __construct()
    {
        $this->app = app();
    }

    public function upload()
    {

    }

    public function getPathByType($type)
    {
        $path = $this->types[$type] ?? "other";
        return $this->makeAttachmentPath($path);
    }

    /**
     * @param string $pathName 文件路径
     * @param int $type
     * @param bool $force
     * @return string
     * @throws Exception
     */
    public function makeAttachmentPath($pathName, int $type = 2, bool $force = false)
    {
        if (!$pathName) return '';
        $path = ltrim(rtrim($pathName));
        switch ($type) {
            case 1:
                $path .= '/' . date('Y');
                break;
            case 2:
                $path .= '/' . date('Y') . '/' . date('m');
                break;
            case 3:
                $path .= '/' . date('Y') . '/' . date('m') . '/' . date('d');
                break;
        }
        try {
//            $uploads_path = app()->getRootPath() . 'public' . '/' . 'uploads' . $path;
            $uploads_path = config('filesystem.disks.public.root');
            if (is_dir($uploads_path) == true
                ||
                mkdir($uploads_path, 0777, true) == true) {
                return trim(str_replace('/', '/', $path), '.');
            } else return '';
        } catch (\Exception $e) {
            if ($force)
                throw new \Exception($e->getMessage());
            return '无法创建文件夹，请检查您的上传目录权限：' . app()->getRootPath() . 'public' . '/' . 'uploads' . '/' . 'attach' . '/';
        }
    }
}
